package com.example.client_anna.module.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.client_anna.R;
import com.example.client_anna.util.adapter.HomeBusinessAdapter;
import com.example.client_anna.util.adapter.HomeImageFirstAdapter;
import com.example.client_anna.util.adapter.HomeImageSecondAdapter;
import com.example.client_anna.util.adapter.ImageAdapter;
import com.example.client_anna.util.entity.Home_Business_Data;
import com.example.client_anna.util.entity.Home_Image;
import com.example.client_anna.network.okhttp3.HttpUtilImpl;
import com.example.client_anna.util.tool.ImageStaticData;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.to.aboomy.pager2banner.Banner;
import com.to.aboomy.pager2banner.IndicatorView;
import com.to.aboomy.pager2banner.ScaleInTransformer;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
public class HomeFragment extends Fragment {

    private View rootView;
    private static final String TAG = "HomeFragment";
    private List<Home_Business_Data> home_business_dataList;

    @Nullable
    @Override
    public View onCreateView(@NonNull  LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //防止资源浪费
        if(rootView==null) {
            rootView = inflater.inflate(R.layout.activity_home_fragment,container,false);
            //轮播图
            initRotation();
            //静态图片数据
            initImageFirst();
            initImageSecond();
            //商家信息
            initBusiness_Data();
        }
        return rootView;
    }
    /*--------------------------------------轮播图-------------------------------------------------*/
    private List<String> list;
    private void initRotation() {
        list = ImageStaticData.getImageList();
        Banner banner = rootView.findViewById(R.id.banner);
        IndicatorView indicatorView = new IndicatorView(getActivity())
                .setIndicatorColor(Color.DKGRAY)
                .setIndicatorSelectorColor(Color.WHITE);
        //设配器添加数据
        ImageAdapter adapter = new ImageAdapter(list);
        //加载
        banner.setIndicator(indicatorView)
                //同时显示3个item
                .setPageMargin(UIUtil.dip2px(getContext(),20),UIUtil.dip2px(getContext(),10))
                //缩放效果
                .addPageTransformer(new ScaleInTransformer())
                .setAdapter(adapter);
    }
    /*-----------------------------------第一行静态数据块--------------------------------------------*/
    private RecyclerView recyclerView;
    private HomeImageFirstAdapter homeImageFirstAdapter;
    private List<Home_Image> home_images = new ArrayList<>();
    private void initImageFirst() {
        //静态数据块
        home_images = ImageStaticData.getFirstData();
        recyclerView = rootView.findViewById(R.id.home_RecyclerView01);
        homeImageFirstAdapter = new HomeImageFirstAdapter(home_images);
        //加载闪烁问题：添加标记tag,tag标记着每一张请求url的图片，加载的时候防止重新加载
        //需要重写adapter的getItemId方法
        homeImageFirstAdapter.setHasStableIds(true);
        //GridLayoutManager布局方式，参数1:Context，参数2:列数
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(),5);
        //加载布局方式
        recyclerView.setLayoutManager(layoutManager);
        //recyclerView布局加载适配器
        recyclerView.setAdapter(homeImageFirstAdapter);
    }
    /*----------------------------------第二行静态数据块---------------------------------------------*/
    private RecyclerView recyclerViewSecond;
    private HomeImageSecondAdapter homeImageSecAdapter;
    private List<Home_Image> home_images_second;
    private void initImageSecond() {
        //静态数据块
        home_images_second = ImageStaticData.getSecondData();
        recyclerViewSecond = rootView.findViewById(R.id.home_RecyclerView02);
        homeImageSecAdapter = new HomeImageSecondAdapter(home_images_second);
        //加载闪烁问题：添加标记tag,tag标记着每一张请求url的图片，加载的时候防止重新加载
        //需要重写adapter的getItemId方法
        homeImageSecAdapter.setHasStableIds(true);
        //GridLayoutManager布局方式，参数1:Context，参数2:列数
        GridLayoutManager layoutManager_Second = new GridLayoutManager(getContext(),5);
        //加载布局方式
        recyclerViewSecond.setLayoutManager(layoutManager_Second);
        //recyclerView布局加载适配器
        recyclerViewSecond.setAdapter(homeImageSecAdapter);
    }
    /*------------------------------------商家信息-------------------------------------------------*/
    private RecyclerView recyclerViewBusiness;
    private HomeBusinessAdapter homeBusinessAdapter;
    private void initBusiness_Data() {
        Home_Okhttp3(200);
    }

    private void Home_Okhttp3(int request){
        //链接的地址
        String address = RequestUrl.getUrl()+"home";
        //创建RequestBody请求体,用于数据的提交
        RequestBody requestBody = new FormBody.Builder()
                .add("id","001")
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 400;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
                refreshLayout.setRefreshing(false);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String responseData=response.body().string();
                //分析返回的数据
                ParesJsonWithGSON(responseData);
                if(request==200){
                    //异步网络请求的数据需要使用handler进行界面更新
                    Message message = new Message();
                    message.what = 200;
                    handler.sendMessage(message);
                }else if(request==1){
                    //异步网络请求的数据需要使用handler进行界面更新
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            }
        });
    }

    private void ParesJsonWithGSON(String jsonData){
        if(jsonData!=null&&!jsonData.isEmpty()) {
            Gson gson = new Gson();
            //转换json数组，使用List<Home_Business_Data>接收
            home_business_dataList = gson.fromJson(jsonData, new TypeToken<List<Home_Business_Data>>(){
            }.getType());
            //控制台显示最新请求的数据
            for (Home_Business_Data i : home_business_dataList) {
                Log.d(TAG, "home_id_new is " + i.getFullminus());
            }
        }
    }

    public Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 400:
                    //请求服务器数据失败
                    Toast.makeText(getActivity(),"网络出错，请等待！",Toast.LENGTH_SHORT).show();
                    break;
                case 200:
                    recyclerViewBusiness = rootView.findViewById(R.id.home_RecyclerView03);
                    homeBusinessAdapter = new HomeBusinessAdapter(home_business_dataList);
                    homeBusinessAdapter.setHasStableIds(true);
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
                    recyclerViewBusiness.setLayoutManager(linearLayoutManager);
                    recyclerViewBusiness.setAdapter(homeBusinessAdapter);
                    break;
                case 1:
                    homeBusinessAdapter = new HomeBusinessAdapter(home_business_dataList);
                    homeBusinessAdapter.notifyDataSetChanged();
                    recyclerViewBusiness.setAdapter(homeBusinessAdapter);
                    refreshLayout.setRefreshing(false);
                    Toast.makeText(getContext(),"刷新完成",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private SwipeRefreshLayout refreshLayout;
    @SuppressLint("ResourceAsColor")
    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        refreshLayout = getActivity().findViewById(R.id.home_Refresh);
        refreshLayout.setColorSchemeResources(R.color.main_color_tone);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Home_Okhttp3(1);
            }
        });
    }

}